#coding: utf-8
import os
import sys
# 安装docx： pip install python_docx
from docx import Document
from docx.shared import Inches
from openpyxl import Workbook
from openpyxl import load_workbook  # 导入模块

class ExcelOp(object):
    def __init__(self, file):
        self.file = file
        self.wb = load_workbook(self.file)
        sheets = self.wb.get_sheet_names()
        self.sheet = sheets[0]
        self.ws = self.wb[self.sheet]

    # 获取表格的总行数和总列数
    def get_row_clo_num(self):
        rows = self.ws.max_row
        columns = self.ws.max_column
        return rows, columns

    # 获取某个单元格的值
    def get_cell_value(self, row, column):
        cell_value = self.ws.cell(row=row, column=column).value
        return cell_value

    # 获取某列的所有值
    def get_col_value(self, column):
        rows = self.ws.max_row
        column_data = []
        for i in range(1, rows + 1):
            cell_value = self.ws.cell(row=i, column=column).value
            column_data.append(cell_value)
        return column_data

    # 获取某行所有值
    def get_row_value(self, row):
        columns = self.ws.max_column
        row_data = []
        for i in range(1, columns + 1):
            cell_value = self.ws.cell(row=row, column=i).value
            row_data.append(cell_value)
        return row_data

    # 设置某个单元格的值
    def set_cell_value(self, row, colunm, cellvalue):
        try:
            self.ws.cell(row=row, column=colunm).value = cellvalue
            self.wb.save(self.file)
        except:
            self.ws.cell(row=row, column=colunm).value = "writefail"
            self.wb.save(self.file)


def replaceStr(old_text, new_text,doc):
    print('op')
    for p in doc.paragraphs:
        if old_text in p.text:
            inline = p.runs
            for i in inline:
                if old_text in i.text:
                    text = i.text.replace(old_text, new_text)
                    i.text = text
    return doc


file_name = input('请输入word文档全路径：')
print(f'典票路径: {file_name}')
excel_name = input('请输入excel文档全路径：')
print(f'excel文档路径: {excel_name}')

#创建 Document 对象，相当于打开一个 word 文档
doc = Document(file_name)
#打开excel文件
ex = ExcelOp(excel_name)
ex_max = ex.get_row_clo_num()
print(ex_max[0])
for i in range(2,ex_max[0]+1):
    old_text = ex.get_cell_value(i,2)
    new_text = ex.get_cell_value(i,3)
    print(new_text)
    doc = replaceStr(old_text, new_text,doc)
print('ok')
#保存文本
doc.save('demo3.docx')
